package com.ssi.report.action;

/** 
 * 
 * 	@author	: Kroekpong Sakulchai
 *  Date 			: 09-MAY-2014
 *  Version 		: Alpha
 *  Team			: Software Solution And Integration
 *   
 * **/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;

import com.ssi.report.common.constant.ReportConstant;
import com.ssi.report.common.utils.SSDateUtil;
import com.ssi.report.common.utils.SSDirectoryUtil;
import com.ssi.report.common.utils.SSLogUtil;
import com.ssi.report.model.ReportModel;
import com.ssi.report.service.ReportService;
import com.ssi.report.service.impl.ReportServiceImpl;

import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;

public class ReportGenerate{
	
	public static SSLogUtil logger = new SSLogUtil();
	
	public void ProcessReport(Date date) {
				
		String template = ReportConstant.CONFIG_REPORT_TEMPLATE_FILENAME_A;
		String output_filename = ReportConstant.CONFIG_REPORT_OUTPUT_FILENAME;
		String dayFormat = ReportConstant.CONFIG_REPORT_TEMPLATE_FORMAT_DAYFOLDER;
		String day_folder = new SimpleDateFormat(dayFormat, Locale.ENGLISH).format(date) + "/";
		String output_dir = ReportConstant.CONFIG_REPORT_OUTPUT_PATH + day_folder;
		
    	/*------ Check Directory For Generate Report-------*/
    	logger.debug("OUTPUT DIRECTORY : "+output_dir);
    	SSDirectoryUtil.existDirectory(output_dir); // Check Existing Directory ####
    	
    	// A) Load Report Data List
        ReportService reportService = new ReportServiceImpl();
        List<ReportModel> reporList = reportService.getReportDataList(date);
        
        // Start Generate Report
        for (ReportModel reportModel : reporList) {
    	
        	String filename = MessageFormat.format(output_filename, new Object[] { 
        			reportModel.getInstument() ,
        			reportModel.getKplusNo(),
        			reportModel.getKtpNo() });
        	
        	String outputFile = output_dir+filename;
        	
        	 // --------Used Template "B"For ISDA Flag is 'Y'----------
        	if(	StringUtils.isNotBlank(reportModel.getFlagIsda()) && ReportConstant.CONFIG_FLAG_Y.equals(reportModel.getFlagIsda())){
        		template = ReportConstant.CONFIG_REPORT_TEMPLATE_FILENAME_B;
        	}
        	
        	GenerateReport(template, reportModel, outputFile);
		}
        
        logger.debug("<<<<<<<<  OUTPUT REPORT NUMBER >>>>>> : " + reporList.size());
	}
	
	public void GenerateReport(String template ,ReportModel reportModel , String outputFile) {
		
		String template_path = ReportConstant.CONFIG_REPORT_TEMPLATE_PATH;
		
		try {
			
			// 1) Load Docx file by filling Velocity template engine and cache it to the registry
	        InputStream in = this.getClass().getResourceAsStream(template_path+template);
	        IXDocReport report = XDocReportRegistry.getRegistry().loadReport( in, TemplateEngineKind.Velocity );
	        IContext context = report.createContext();
	        context.put( ReportConstant.CONFIG_REPORT_MAP , reportModel ); // merging model data to report

	        logger.debug("[OUTPUT FILE] : "+outputFile);

            OutputStream out = new FileOutputStream( new File( outputFile ) );
            report.process( context, out );
	           
		} catch (IOException | XDocReportException e) {
			e.printStackTrace();
		}
	}
	

    public static void main(String[] args) {
		try {
			
			Date date = new Date();
			
			if("TRUE".equals(ReportConstant.CONFIG_APP_TEST)){
				String sysdate = ReportConstant.getProp(ReportConstant.CONFIG_REPORT, "application.softsai.test.date");
				date = SSDateUtil.stringToDate(sysdate);
				logger.debug(" #####----- [TEST MODE] -----##### ");
			}else{
				logger.debug(" #####----- [REPORT START] -----##### ");
			}
			
			logger.debug("[DATE] : "+date);
			
	    	ReportGenerate reportGenerate = new ReportGenerate();
	    	reportGenerate.ProcessReport(date);
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}
    			
    }
}
